package com.universal.generator;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

/**
 * 代码生成器例子
 *
 * @author austin
 * @data 2022/11/14 19:04
 */
@Slf4j
public class UniversalCodeGenerator {

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help);
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }


    /**
     * RUN THIS
     */
    public static void main(String[] args) {

        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        //final String projectPath = System.getProperty("user.dir");
        final String projectPath = "E:/flt/";
        //gc.setOutputDir(projectPath + "/src/main/java");
        gc.setOutputDir(projectPath + "/universal-service-starter-user/src/main/java");
        gc.setAuthor("austin");
        gc.setOpen(false);

        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/user_center?useUnicode=true&useSSL=false&characterEncoding=utf8");

        dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");

        dsc.setUsername("root");
        dsc.setPassword("admin");
        mpg.setDataSource(dsc);
        // 包配置
        final PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("模块名"));
        pc.setModuleName("user");
        //pc.setParent("com.universal.modules.user");
        pc.setParent("universal-business-dev-kit-generator");
        pc.setMapper("dao");

        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<>();
                //特殊字符的注入
                map.put("special", "$");
                map.put("dtoRouting", "com.universal.modules.user.dto");
                this.setMap(map);
            }
        };
        List<FileOutConfig> focList = new ArrayList<>();

        focList.add(new FileOutConfig("/templates/api.java.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return projectPath + "/universal-service-user-api/src/main/java/com/universal/modules/user/api/"
                        + tableInfo.getEntityName() + "Api" + StringPool.DOT_JAVA;
            }
        });
        focList.add(new FileOutConfig("/templates/api.feign.java.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return projectPath + "/universal-service-user-feign/src/main/java/com/universal/modules/" + pc.getModuleName() + "/api/feign"
                        + "/I" + tableInfo.getEntityName() + "Feign" + StringPool.DOT_JAVA;
            }
        });

        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return projectPath + "/universal-service-starter-user/src/main/java/com/universal/modules/" + pc.getModuleName() + "/mapper"
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });

        //focList.add(new FileOutConfig("/templates/entity.java.ftl") {
        //    @Override
        //    public String outputFile(TableInfo tableInfo) {
        //        // 自定义输入文件名称
        //        return projectPath + "/universal-service-user-model/src/main/java/com/universal/modules/" + pc.getModuleName() + "/entity"
        //                + "/" + tableInfo.getEntityName() + StringPool.DOT_JAVA;
        //    }
        //});

        focList.add(new FileOutConfig("/templates/entityDto.java.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return projectPath + "/universal-service-user-model/src/main/java/com/universal/modules/" + pc.getModuleName() + "/dto"
                        + "/" + tableInfo.getEntityName() + "DTO" + StringPool.DOT_JAVA;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        mpg.setTemplate(new TemplateConfig().setXml(null));

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setSuperEntityClass("com.universal.base.entity.BaseEntity");
        strategy.setSuperControllerClass("com.universal.base.controller.BaseController");
        strategy.setSuperServiceClass("com.universal.base.service.IBaseService");
        strategy.setInclude(scanner("表名"));
        strategy.setSuperEntityColumns("id", "deleted", "create_by", "create_time", "update_time", "update_by");
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix("");

        strategy.setRestControllerStyle(true);
        strategy.setEntityTableFieldAnnotationEnable(true);

        mpg.setStrategy(strategy);
        // 选择 freemarker 引擎需要指定如下加，注意 pom 依赖必须有！
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}
